# This file is part of WSAP web sockets server module.
# Copyright (c) 2010 Brandon Orther. All rights reserved.

from core import *
import json

class json_envelope:
    """
    The WSAP json envelope is just a helper function to send data back to the client in a
    standardized way.
    """

    @staticmethod
    def response(task, values):
        """
        Build a JSON object which holds the response values to push to a client. A WebSocket frame
        is then wrapped around the created JSON string before it is returned.
        
        Params:
            (String) task:  The name of the task you are requsting be called
            (Mixed) values: The resonpose values.  This can be any datatype

        Return:
            (String)    JSON string.
        """
        try:
            return wsFrame(json.dumps({"task": str(task), "values": values}))
        except:
            return False

    @staticmethod
    def error(error_msg, task=False, values=False):
        """
        Build a JSON object which holds error message and response values to push to a client. A
        WebSocket frame is then wrapped around the created JSON string before it is returned.

        Params:
            (String) error_msg: Error message to be returned
            (String)      task: The name of the task you are requsting be called
            (Mixed)     values: The resonpose values.  This can be any datatype
        Return:
            (String)    JSON string.
        """

        try:
            return wsFrame(json.dumps({"error": True, "task": str(task), "values": values, "error_msg": str(error_msg)}))
        except:
            return False
